<template>
    <div class="edit-article">
        <div class="fix-header">
            <el-page-header @back="goBack" content="文章编辑">
            </el-page-header>
            <div class="save">
                <el-button size="small" type="primary" @click="submitForm">保存</el-button>
            </div>
        </div>
        <el-form label-width="100px" class="edit-form">
            <el-form-item label="标题">
                <el-input size="small" v-model="formData.title" style="width: 300px" placeholder="请输入标题" />
            </el-form-item>


            <el-form-item label="信息来源">
                <el-select size="small" v-model="formData.classify" placeholder="请选择信息来源" filterable>
                    <el-option v-for="(item, index) in classifyOptions" :key="index" :label="item.label"
                        :value="item.value" />
                </el-select>
                <div class="classIfy-tips">
                    没找到信息来源，试试
                    <add-class-dialog @update="getClassiyOptions" />
                    信息来源
                </div>
            </el-form-item>

            <el-form-item label="封面">
                <template v-if="!formData.poster">
                    <el-switch size="small" v-model="openPoster" active-text="开启"></el-switch>

                    <upload-picture :url.sync="formData.poster" v-if="openPoster" prefix="article/posters">
                    </upload-picture>

                </template>

                <template v-else>
                    <upload-picture :url.sync="formData.poster" prefix="article/posters">
                    </upload-picture>
                </template>

            </el-form-item>


            <el-form-item label="发表时间">
                <el-date-picker size="small" v-model="formData.publishTime" type="datetime" placeholder="选择日期时间"
                    value-format="yyyy-MM-dd HH:mm:ss" />
            </el-form-item>
            <el-form-item label="内容">
                <RichTextEditor ref="myWangEditor" v-model="formData.detail" />
            </el-form-item>
        </el-form>
    </div>
</template>

<script>
import RichTextEditor from "@/components/RichTextEditor";
import addClassDialog from "./components/add-classIfy-dialog.vue";

export default {
    name: "EditArticle", // 将组件名改为多单词形式

    components: {
        RichTextEditor,
        addClassDialog,
    },
    data() {
        return {
            openPoster: false,
            formData: {
                title: "",
                classify: "",
                poster: "",
                publishTime: new Date(),
                detail: "",
            },
            classifyOptions: [],
        };
    },
    mounted() {
        this.init();
        this.getClassiyOptions();
    },
    methods: {
        async init() {
            const { type, articleId, publishTime } = this.$route.query;
            if (type === "edit") {
                const data = await this.getArticleInfo(articleId);
                console.log("data", data);

                this.$nextTick(() => {
                    this.formData = {
                        ...data,
                        publishTime: new Date(publishTime),
                    };
                    this.$refs.myWangEditor.setHtml(data.detail);
                });
            }
        },

        chooseFile() {
            this.$refs.uploadInput.click(); // 触发文件选择框
        },

        async getClassiyOptions() {
            const { data } = await this.$fetch.get("/api/article/classIfy/list", {});
            this.classifyOptions = data.map((item) => ({
                ...item,
                label: item.value,
            }));
        },

        handleFileChange(event) {
            const file = event.target.files[0];

            if (file && /\.(jpg|jpeg|png|gif)$/i.test(file.name)) {
                this.readFile(file);
            } else {
                this.$message.error("请仅选择图片文件");
            }
        },

        async getArticleInfo(id) {
            const { data } = await this.$fetch.get(`/api/article/${id}`);
            return data || {};
        },

        async submitForm() {
            const loading = this.$loading();
            const { type, directoryId, articleId } = this.$route.query;

            const detail = this.$refs.myWangEditor.getHtml();

            const params = {
                ...this.formData,
                articleId,
                detail,
                type,
                directoryId,
            };

            try {
                const { code } = await this.$fetch.post(
                    "/api/directory-article/bindOrUpdate",
                    params
                );

                if (code === 0) {
                    this.$message.success(type === "add" ? "添加成功" : "修改成功");

                    this.goBack();
                }
                loading.close();
            } catch (error) {
                loading.close();
                this.$message.success(error.message);
            }
        },

        goBack() {
            this.$router.push({
                path: "/directory/article",
            });
        },
        previewContent() {
            const detail = this.$refs.myWangEditor.getEditor().getText();
            console.log(`预览内容：\n${detail}`);
        },
    },
};
</script>

<style scoped lang="less">

.edit-article {
    height: 100%;
    flex-direction: column;
    overflow-y: auto;

    .edit-form {
        flex: 1;
    }
}
.fix-header {
    display: flex;
    margin-bottom: 10px;
    position: sticky;


    .save {
        position: absolute;
        right: 60px;
        top: 0;
    }

    .cancel {
        margin-left: 15px;
    }
}

#editor {
    width: 100%;
    height: 300px;
}

.classIfy-tips {
    color: #999;
    position: absolute;
    left: 224px;
    top: 0;
    display: flex;
}

::v-deep .preview-image {
height: 100px;
}
::v-deep .el-form-item{
    margin-bottom: 10px;
}

</style>
